import _ from 'lodash';
import { useQuery } from '@tanstack/react-query';
import postApis from '../../apis/posts';
import ErrorInfo from '../ui/ErrorInfo';

type Props = {
  collectionId: number | string | null | undefined;
  children: (collection: PostCollection) => React.ReactNode;
};

export default function OnlyIfMyPostCollectionExists({ collectionId, children }: Props) {
  // TODO: 错误回调
  if (_.isNil(collectionId)) {
    return <div>前端用错了吧？!</div>;
  }

  const cid = _.isString(collectionId) ? +collectionId : collectionId;
  if (!_.isInteger(cid) || cid < 1) {
    return <div>参数错误!</div>;
  }

  const { status, data, error } = useQuery({
    queryKey: ['post-collection-by-id', cid],
    queryFn: () => postApis.getPostCollectionById(cid),
  });

  if (status === 'pending') {
    return <div>Loading</div>;
  }

  if (status === 'error') {
    return <ErrorInfo error={error} />;
  }

  if (data.updatable) {
    return <div>{children(data)}</div>;
  } else {
    return <div>这不是你的文章分组!</div>;
  }
}
